package com.jiyun.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.pojo.Dept;
import com.jiyun.pojo.Emp;
import com.jiyun.pojo.EmpDTO;
import com.jiyun.service.EmpService;
import com.jiyun.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
public class EmpController {

    @Autowired
    EmpService empService;

    @RequestMapping("findPage")
    public Page<Emp> findPage(Integer pageNum, Integer pageSize, @RequestBody EmpDTO empDTO){
        return empService.findPage(pageNum,pageSize,empDTO);
    }

    @RequestMapping("findDeptList")
    public List<Dept> findDeptList(){
        return empService.findDeptList();
    }

    @RequestMapping("add")
    public void add(@RequestBody Emp emp){
        empService.add(emp);
    }
    @RequestMapping("update")
    public void update(@RequestBody Emp emp){
        empService.update(emp);
    }
    @RequestMapping("deleteById")
    public void deleteById(Integer id){
        empService.deleteById(id);
    }
    @RequestMapping("deleteBatch")
    public void deleteBatch(@RequestBody List<Emp> empList){
        empService.deleteBatch(empList);
    }


    @RequestMapping("findById")
    public Emp findById(Integer id){
        return empService.findById(id);
    }

    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        // 先查询所有数据
        List<Emp> list = empService.findAll();
        // 1.响应对象  2.数据  3.文件名称  4.sheet名称
        ExcelUtils.exportExcel(response,list,"员工信息","员工列表");

    }

    @RequestMapping("uploadExcel")
    public String uploadExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Emp.class, new ReadListener<Emp>() {
            // 回调函数
            // 每读取一行，调用一次
            @Override
            public void invoke(Emp emp, AnalysisContext analysisContext) {
                String deptName = emp.getDeptName();
                Integer did = empService.findByDeptName(deptName);
                emp.setDid(did);
                emp.setSex(emp.getSex().equals("男")?"0":"1");
                empService.add(emp);
            }
            // 所有读取完成之后，调用一次
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {

            }
        }).sheet(0).doRead();

        return "0";
    }

}
